<template>
  <div class="stat-analy">
    <div class="left-main white-wrap">
      <span :class="['anchor',curIndex===index?'active':'']" v-for="(item,index) in blocks" @click="jump(index)" v-bind:key="item.name">
        <i :class="['icon iconfont',item.icon]"></i>{{item.name}}</span>
    </div>
    <div class="right-main">
      <div class="white-wrap top-opt clearFix">
        <!--<span class="area">地区:-->
        <!--<j-select v-model="area" :selectedIndex="selectedIndex" :initItems="initItems" displayKey="name" @change="change"></j-select>-->
        <!--</span>-->
        <span class="mgl-50 date-picker">时间范围:
          <j-date-picker v-model="startTime" :max="maxTime" @change="fliterChange('t')"></j-date-picker>
          <span class="space-mark"></span>
          <j-date-picker v-model="endTime" :min="startTime" :max="curTime" @change="fliterChange('t')"></j-date-picker>
        </span>
        <!--地区、预览报告、下载报告 这期隐藏,后续放开-->
        <div class="fr">
          <!-- <a class="preview">
            <i class="icon iconfont icon-2yulan"></i>预览报告</a> -->
          <a class="download" @click.prevent="pic" :disabled="isDisable">
            <i class="icon iconfont icon-xiazai"></i>{{downState}}</a>
        </div>
      </div>
      <div class="white-wrap mgt-20" id="whole2">
        <h5>企业风险监测预警统计分析报告</h5>
        <span class="whole" id="main" ref="jumpContent1">{{area}}企业风险预警整体情况：</span>
        <div class="whole-detail">
          <div class="stat-num clearFix">
            <span class="num-item" v-for="(item,index) in indicators" :key="item">{{item}}
              <span class="num">{{indicatorNum[index]|alternative}}</span>家
              <!--{{index===4?'次':'家'}}-->
            </span>
          </div>
          <div class="table-chart clearFix">
            <div class="fl">
              <table class="table-fixed">
                <thead>
                  <th>烽火值</th>
                  <th>数量(家)</th>
                </thead>
                <tbody>
                  <tr v-for="item in levels" v-bind:key="item.name">
                    <td>{{item.num}}</td>
                    <td>{{item.value|alternative}}</td>
                  </tr>
                </tbody>
              </table>
            </div>
            <div class="fl">
              <div class="chart" id="riskLevel" v-if="chartStates[8].code===Code.Success||chartStates[8].code===Code.Loading"></div>
            </div>
          </div>
        </div>

        <div class="block-content" id="block1">
          <div class="block-title" ref="jumpContent2">预警企业处理分析</div>
          <div class="chart-label">
            <div class="label-area clearFix">
              <div>
                <p>近一周处理</p>
                <p>近一个月处理：</p>
                <p>历史处理：</p>
              </div>
              <div class="analy-num">
                <p>{{weekDNum|alternative}}家</p>
                <p>{{monthDNum|alternative}}家</p>
                <p>{{historyDNum|alternative}}家</p>
              </div>
            </div>
            <div class="chart" id="warningAnalysis" v-if="chartStates[0].code===Code.Success||chartStates[0].code===Code.Loading"></div>
            <jPageMsg mode='f' :code="chartStates[0].code" :msg="chartStates[0].msg" v-else></jPageMsg>
          </div>
        </div>

        <div class="block-content" id="block2">
          <div class="block-title" ref="jumpContent3">风险企业趋势图</div>
          <div class="line-chart mgt-b" id="riskTrend" v-if="chartStates[1].code===Code.Success||chartStates[1].code===Code.Loading"></div>
          <jPageMsg mode='f' :code="chartStates[1].code" :msg="chartStates[1].msg" v-else></jPageMsg>
        </div>
        <div class="block-content" id="block3">
          <div class="block-title" ref="jumpContent4">TOP10风险企业</div>
          <div class="top-risk">
            <table class="table-fixed">
              <thead>
                <th>序号</th>
                <th>TOP10企业名称</th>
                <th>风险类型</th>
                <th>烽火值</th>
              </thead>
              <col style="width: 15%" />
              <col style="width: 35%" />
              <col style="width: 35%" />
              <col style="width: 15%" />
              <tbody v-if="list.length>0&(listState.code===Code.Success||listState.code===Code.Loading)">
                <tr v-for="(item,index) in list" v-bind:key="item.id">
                  <td>{{index+1}}</td>
                  <router-link class="ent-name" :title="item.entName" tag="td" :to="{name:'baseinfo', query: {entid:item.id,entname:item.entName }}">{{item.entName}}</router-link>
                  <td class="color-999">{{item.predictionType}}</td>
                  <td>
                    <span :class="getValueColor(item.beaconValue)">{{item.beaconValue|alternative}}</span>
                  </td>
                </tr>
              </tbody>
            </table>
            <jPageMsg mode='f' :code="listState.code" :msg="listState.msg" v-if="list.length===0||(listState.code!==Code.Success&listState.code!==Code.Loading)"></jPageMsg>
          </div>
        </div>

        <div class="block-content clearFix" id="block4">
          <div class="block-title" ref="jumpContent5">风险企业信息分析</div>
          <div class="chart-block">
            <span class="chart-title">风险类型占比</span>
            <div class="chart" id="riskType" v-if="chartStates[2].code===Code.Success||chartStates[2].code===Code.Loading"></div>
            <jPageMsg class="err-block" mode='f' :code="chartStates[2].code" :msg="chartStates[2].msg" v-else></jPageMsg>
          </div>
          <div class="chart-block">
            <span class="chart-title">注册资金分布</span>
            <div class="chart" id="regisCapital" v-if="chartStates[3].code===Code.Success||chartStates[3].code===Code.Loading"></div>
            <jPageMsg class="err-block" mode='f' :code="chartStates[3].code" :msg="chartStates[3].msg" v-else></jPageMsg>
          </div>
          <div class="chart-block">
            <span class="chart-title">成立时间分布</span>
            <div class="chart" id="foundingTime" v-if="chartStates[4].code===Code.Success||chartStates[4].code===Code.Loading"></div>
            <jPageMsg class="err-block" mode='f' :code="chartStates[4].code" :msg="chartStates[4].msg" v-else></jPageMsg>
          </div>
          <div class="chart-block">
            <span class="chart-title">风险企业行业分布</span>
            <div class="chart" id="entCategory" v-if="chartStates[5].code===Code.Success||chartStates[5].code===Code.Loading"></div>
            <jPageMsg class="err-block" mode='f' :code="chartStates[5].code" :msg="chartStates[5].msg" v-else></jPageMsg>
          </div>
          <div class="chart-block">
            <span class="chart-title">舆情来源排行榜</span>
            <div class="chart" id="opinionSource" v-if="chartStates[6].code===Code.Success||chartStates[6].code===Code.Loading"></div>
            <jPageMsg class="err-block" mode='f' :code="chartStates[6].code" :msg="chartStates[6].msg" v-else></jPageMsg>
          </div>
          <div class="chart-block">
            <span class="chart-title">舆情关键词</span>
            <div class="chart" id="opinionKeywords" v-if="chartStates[7].code===Code.Success||chartStates[7].code===Code.Loading"></div>
            <jPageMsg class="err-block" mode='f' :code="chartStates[7].code" :msg="chartStates[7].msg" v-else></jPageMsg>
          </div>
        </div>
      </div>
    </div>
    <j-loading mode='f' v-show="isShowLoading"></j-loading>
    <!-- <img :src="imBase64"/> -->
  </div>
</template>
<script>
import { jSelect, jDatePicker, jPageMsg, jLoading } from '../../components'
import { PieCharts } from '../../assets/js/chart/pieChart'
import { LineBarChart } from '../../assets/js/chart/lineBarChart'
import { GraphChart } from '../../assets/js/chart/graphChart'
import { Code } from '../../assets/js/operaCode'
import { statAnaly as api, downLoads as dpi } from '../../api'
import html2canvas from 'html2canvas'
// import Axios from 'axios'
export default {
  components: { jSelect, jDatePicker, jPageMsg, jLoading },
  data() {
    return {
      downState: '下载报告',
      token:'',
      listState: {
        code: Code.Loading,
        msg: ''
      },
      isShowLoading: false,
      Code: Code,
      curIndex: 0,
      selectedIndex: 0,
      startTime: '',
      endTime: '',
      //      initItems: [{ name: '天津市' }],
      area: '',
      indicators: [
        '本区域内企业总量',
        '进行监测企业总量',
        //        '风险预警',
        '预警企业',
        //        '共处理预警企业',
        '共处理监管企业'
        //        '未处理企业'
      ],
      indicatorNum: [],
      curConfig:{},
      levels: [{name: '高风险', num: '80-100'}, {name: '中风险', num: '60-80'}, {name: '低风险', num: '40-60'}, {name: '无风险', num: '40以下'}],
      weekDNum: '',
      monthDNum: '',
      historyDNum: '',
      blocks: [
        { name: '整体情况', id: 'main', icon: 'icon-zhuzhuangfenbu' },
        {
          name: '预警企业处理分析',
          id: 'block1',
          icon: 'icon-msnui-report-map'
        },
        { name: '风险企业趋势图', id: 'block2', icon: 'icon-icon1' },
        { name: 'TOP10风险企业', id: 'block3', icon: 'icon-TOPyuangongfenxi' },
        { name: '风险企业信息分析', id: 'block4', icon: 'icon-cc-pie-chart' }
      ],
      list: [],
      imBase64: '',
      baseUrl: '',
      isDisable: false
    }
  },
  computed: {
    maxTime() {
      if ((new Date().valueOf() - new Date(this.endTime).valueOf()) > 0) {
        return this.endTime
      } else {
        return this.curTime
      }
    },
    curTime() {
      let date = new Date()
      let year = date.getFullYear()
      let month = date.getMonth() > 9 ? (date.getMonth() + 1) : ('0' + (date.getMonth() + 1))
      let day = date.getDate() > 9 ? date.getDate() : ('0' + date.getDate())
      return year + '-' + month + '-' + day
    },
    chartStates() {
      let arr = []
      for (let i = 0; i < 9; i++) {
        let item = { code: Code.Loading, msg: '' }
        arr.push(item)
      }
      return arr
    },
    globalParams() {
      let params = {}
      if (this.startTime !== '') {
        params.startTime = this.startTime + ' 00:00:00'
      }
      if (this.endTime !== '') {
        params.endTime = this.endTime + ' 23:59:59'
      }
      return params
    }
  },
  methods: {
    pic() {
      html2canvas(document.getElementById('whole2'), { backgroundColor: '#fff' })
        .then((canvas) => {
          this.convertCanvasToImage(canvas)
        }).catch((e) => {
        })
    },
    convertCanvasToImage(canvas) {
      this.downState = '下载中...'
      this.isDisable = true
      var image = new Image()
      image.src = canvas.toDataURL('image/png')
      this.imBase64 = image.src
      let params = {
        imgStr: this.imBase64
        // imgStr: '123456'
      }
      dpi.getExportStatistics(params).then(res => {
        location.href = this.baseUrl + '/statisticsPage/downloadPicToPdf?name=' + encodeURI(encodeURI(res.data))
        this.isDisable = false
        this.downState = '下载报告'
      }).catch(res => {
        this.isDisable = false
      })
      // this.saveFile(image.src, '统计分析.png')
    },
    //  下载
    saveFile(imgData, filename) {
      var saveLink = document.createElementNS('http://www.w3.org/1999/xhtml', 'a')
      saveLink.href = imgData
      saveLink.download = filename
      var event = document.createEvent('MouseEvents')
      event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
      saveLink.dispatchEvent(event)
    },
    getValueColor(val) {
      let level = 'no'
      if (val < 40) {
        level = 'no'
      } else if (val >= 40 && val < 60) {
        level = 'l'
      } else if (val >= 60 && val < 80) {
        level = 'm'
      } else if (val >= 80) {
        level = 'h'
      }
      return 'color-risk-' + level
    },
    onScroll(params) {
      this.curIndex = params.index
      document.body.scrollTop = params.offsetTop
      document.documentElement.scrollTop = params.offsetTop
    },
    jump(index) {
      let curIndex = index + 1
      let target = 'jumpContent' + curIndex
      let offsetTop = this.$refs[target].offsetTop - 70
      let params = {
        index,
        offsetTop
      }
      this.onScroll(params)
    },
    // 企业风险预警整体情况
    getWholeSituation() {
      this.chartStates[8].code = Code.Loading
      api
        .getWholeSituation(this.globalParams)
        .then(rst => {
          let data = rst.data
          if (data) {
            this.indicatorNum = [data.total, data.controlEnt, data.riskEnt, data.doEnt]
            // console.log(this.indicatorNum)
            this.levels[0]['value'] = data.highRisk
            this.levels[1]['value'] = data.relevanceRisk
            this.levels[2]['value'] = data.opinionRisk
            this.levels[3]['value'] = data.nullRisk
            this.chartStates[8].code = Code.Success
            PieCharts.drawPieOne('riskLevel', {seriesData: this.levels})
          } else {
            this.chartStates[8].code = Code.NoData
          }
        })
        .catch(err => {
          this.chartStates[8] = err
        })
    },
    // 预警企业处理分析
    getWarningAnaly() {
      this.chartStates[0].code = Code.Loading
      api
        .getWarningAnaly(this.globalParams)
        .then(rst => {
          // console.log('预警企业处理分析', rst.data)
          this.weekDNum = rst.data.week
          this.monthDNum = rst.data.mouth
          this.historyDNum = rst.data.history
          this.chartStates[0].code = Code.Success
          // console.log(rst)
          LineBarChart.drawBar('warningAnalysis', rst.data)
        })
        .catch(err => {
          this.chartStates[0] = err
        })
    },
    // 风险企业趋势图
    getRiskTrend() {
      this.chartStates[1].code = Code.Loading
      api
        .getRiskTrend(this.globalParams)
        .then(rst => {
          let seriesData = (rst.data && rst.data.seriesData) ? rst.data.seriesData : []
          if (seriesData.length > 0) {
            let data = {
              xAxisData: (rst.data && rst.data.xAxisData) ? rst.data.xAxisData : [],
              seriesData: [
                {
                  data: seriesData
                }
              ]
            }
            this.chartStates[1].code = Code.Success
            LineBarChart.drawLine('riskTrend', data)
          } else {
            this.setNoData(1)
          }
        })
        .catch(err => {
          this.chartStates[1] = err
        })
    },
    // TOP10风险企业
    getTopTen() {
      this.listState.code = Code.Loading
      api
        .getTopTen(this.globalParams)
        .then(rst => {
          if (rst.data.length > 0) {
            this.listState.code = Code.Success
            this.list = rst.data
            this.list.map((item, index) => {
              if (item.predictionType.indexOf(',烽火指数偏高')) {
                item.predictionType = item.predictionType.replace(',烽火指数偏高', '')
              }
            })
          } else {
            this.listState.code = Code.NoData
          }
        })
        .catch(err => {
          this.listState = err
        })
    },
    // 风险企业信息分析----风险类型占比
    getRiskType() {
      this.chartStates[2].code = Code.Loading
      api
        .getRiskType(this.globalParams)
        .then(rst => {
          let rawData = rst.data ? rst.data : []
          if (rawData.length > 0) {
            this.chartStates[2].code = Code.Success
            PieCharts.drawPieTwo('riskType', {seriesData: rawData})
          } else {
            this.setNoData(2)
          }
        })
        .catch(err => {
          this.chartStates[2] = err
        })
    },
    // 风险企业信息分析----注册资金分布
    getRegisCapital() {
      this.chartStates[3].code = Code.Loading
      api
        .getRegisCapital(this.globalParams)
        .then(rst => {
          let rawData = rst.data ? rst.data : []
          if (rawData.length > 0) {
            this.chartStates[3].code = Code.Success
            PieCharts.drawPieTwo('regisCapital', {seriesData: rawData})
          } else {
            this.setNoData(3)
          }
        })
        .catch(err => {
          this.chartStates[3] = err
        })
    },
    // 风险企业信息分析----成立时间分布
    getFoundingTime() {
      this.chartStates[4].code = Code.Loading
      api
        .getFoundingTime(this.globalParams)
        .then(rst => {
          if (rst.data.length > 0) {
            this.chartStates[4].code = Code.Success
            PieCharts.drawPieTwo('foundingTime', { seriesData: rst.data })
          } else {
            this.setNoData(4)
          }
        })
        .catch(err => {
          this.chartStates[4] = err
        })
    },
    // 风险企业信息分析----风险企业行业分布
    creatCompare(propertyName) {
      return function(obj1, obj2) {
        let value1 = obj1[propertyName]
        let value2 = obj2[propertyName]
        if (propertyName === 'name') {
          if (value1.length < value2.length) {
            return -1
          } else if (value1.length > value2.length) {
            return 1
          } else {
            return 0
          }
        } else {
          if (value1 < value2) {
            return -1
          } else if (value1 > value2) {
            return 1
          } else {
            return 0
          }
        }
      }
    },
    getEntCategory() {
      this.chartStates[5].code = Code.Loading
      api
        .getEntCategory(this.globalParams)
        .then(rst => {
          if (rst.data.length > 0) {
            //   this.chartStates[5].code = Code.Success
            //   let xAxisData = []
            //   rst.data.map(item => {
            //     xAxisData.push(item.name)
            //   })
            //   let data = {
            //     xAxisData: xAxisData,
            //     seriesData: [
            //       {
            //         data: rst.data
            //       }
            //     ]
            //   }
            //   LineBarChart.drawBar('entCategory', { ...data, chartType: '1' })
            let names = []
            let values = []
            let group = rst.data
            group.sort(this.creatCompare('name'))
            group.map(item => {
              names.push(item.name)
            })
            group.map(item => {
              values.push(item.value)
            })
            let data = {
              name: Object.values(names),
              value: Object.values(values)
            }
            this.getcharts('entCategory', data)
          } else {
            this.setNoData(5)
          }
        })
        .catch(err => {
          this.chartStates[5] = err
        })
    },
    // 风险企业信息分析----舆情来源排行榜
    getOpinionSource() {
      this.chartStates[6].code = Code.Loading
      api
        .getOpinionSource(this.globalParams)
        .then(rst => {
          if (rst.data.groupResultVos) {
            let names = []
            let values = []
            let group = rst.data.groupResultVos
            group.sort(this.creatCompare('name'))
            // console.log(group)
            group.map(item => {
              if (item.name) {
                names.push(item.name)
              }
            })
            group.map(item => {
              if (item.name) {
                values.push(item.value)
              }
            })
            let data = {
              name: Object.values(names),
              value: Object.values(values)
            }
            this.getcharts('opinionSource', data)
          } else {
            this.setNoData(6)
          }
        })
        .catch(err => {
          this.chartStates[6] = err
        })
    },
    getcharts(id, data) {
      const chartDom = document.getElementById(id)
      // eslint-disable-next-line
      const chart = echarts.init(chartDom)
      let option = {
        color: ['#3398DB'],
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '7%',
          containLabel: true
        },
        xAxis: [{
          type: 'category',
          data: data.name,
          axisTick: {
            show: false,
            alignWithLabel: true,
            color: '#ccc'
          },
          axisLine: {
            lineStyle: {
              color: '#ccc'
            }
          },
          axisLabel: {
            color: '#808080',
            rotate: 45
          }
        }],
        yAxis: [{
          type: 'value',
          axisLine: {
            lineStyle: {
              color: '#ccc'
            }
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            color: '#808080'
          }
        }],
        series: [{
          name: '',
          type: 'bar',
          barWidth: '10%',
          itemStyle: {
            normal: {
              // eslint-disable-next-line
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                offset: 0,
                color: '#20aeff'
              },
              {
                offset: 1,
                color: '#17a1ef'
              }
              ])
            }
          },
          data: data.value
        }]
      }
      chart.setOption(option)
    },
    // 风险企业信息分析----舆情关键词
    getOpinionKeywords() {
      this.chartStates[7].code = Code.Loading
      api
        .getOpinionKeywords(this.globalParams)
        .then(rst => {
          let rawData =
          rst.data && rst.data.groupResultVos ? rst.data.groupResultVos : []
          if (rawData.length > 0) {
            this.chartStates[7].code = Code.Success
            // console.log(rawData)
            GraphChart.drawWord('opinionKeywords', { data: rawData })
          } else {
            this.setNoData(7)
          }
        })
        .catch(err => {
          this.chartStates[7] = err
        })
    },
    setNoData(index) {
      this.chartStates[index].code = Code.NoData
      this.chartStates[index].msg = 'b'
    },
    fliterChange(type) {
      if (type) {
        this.isShowLoading = true
        setTimeout(() => {
          this.isShowLoading = false
        }, 1000)
      }
      this.getWholeSituation()
      this.getRiskTrend()
      this.getTopTen()
      this.getRiskType()
      this.getRegisCapital()
      this.getFoundingTime()
      this.getEntCategory()
      this.getOpinionSource()
      this.getOpinionKeywords()
    }
  },
  destroyed() {

  },
  mounted() {
    this.getWarningAnaly()
    // 历史处理
    this.fliterChange()
    this.baseUrl = window.api_host
    let area = this.$store.state.user.userInfo.realName
    this.token = JSON.parse(sessionStorage.getItem("user")).token || ''
    this.area = area || ''
    this.curConfig = {
      timeout: 600000,
      headers: {
        Authorization: this.token
      }
    }
  }
}
</script>
<style lang="scss" scoped>
@import '../../assets/css/statAnaly.scss';
</style>


// WEBPACK FOOTER //
// src/view/statAnaly/statAnaly.vue